package com.ucode.search.crm.service.impl;

import java.util.List;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ucode.search.crm.model.ESCustomer;
import com.ucode.search.crm.service.ESCustomerService;
import com.ucode.springboot.starter.ESsearch.repository.ElasticsearchSearchTemplate;
import com.ucode.springboot.starter.ESsearch.repository.query.Advanc;
import com.ucode.springboot.starter.ESsearch.repository.query.HighLight;
import com.ucode.springboot.starter.ESsearch.repository.query.PageSortHighLight;
import com.ucode.tool.base.Paginator;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

@Service
public class ESCustomerServiceImpl implements ESCustomerService {

    private static Log log = LogFactory.get(ESCustomerServiceImpl.class);
    
    @Autowired
    private ElasticsearchSearchTemplate<ESCustomer, Long> esSearchTemplate;
    
    @Override
    public Paginator<ESCustomer> searchByUser(List<Long> userIds, Integer prole, String keyword,Integer level,Integer source, Integer pageNum, Integer pageSize) throws Exception {
        
        PageSortHighLight pageSortHighLight = new PageSortHighLight(pageNum, pageSize);
        
        //非公海
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("ownerUserId", 0L));
        
        if(StrUtil.isNotBlank(keyword)){
            //为了提高通配符模糊查询效率 建议输入关键字的长度
           QueryBuilder keywordQueryBuilder = QueryBuilders.boolQuery().should(QueryBuilders.matchPhrasePrefixQuery("name", keyword).maxExpansions(50))
                   .should(QueryBuilders.queryStringQuery("*"+keyword+"*").field("mobile"))
                   .should(QueryBuilders.queryStringQuery("*"+keyword+"*").field("telephone"));
           
           queryBuilder = queryBuilder.must(keywordQueryBuilder);
           
           HighLight highLight = pageSortHighLight.getHighLight();
           highLight.field("name");
           highLight.field("mobile");
           highLight.field("telephone");
        }
        
        if(source != null ){
            queryBuilder = queryBuilder.must(QueryBuilders.termQuery("source", source));
        }
        
        if(level != null ){
            queryBuilder = queryBuilder.must(QueryBuilders.termQuery("level", level));
        }
        
        if(CollUtil.isNotEmpty(userIds)){
            QueryBuilder userIdsQueryBuilder = null;
            String userIdsStr = StrUtil.join(" ", userIds);
//            0->全部,1->我负责的客户2->下属负责的客户3->我协作的客户4->下属协作的客户
            if(0 == prole){
                //userIds 的全部客户
                userIdsQueryBuilder = QueryBuilders.multiMatchQuery(userIdsStr, "ownerUserIdStr","collaborator");
            }else if(1 == prole){
                //userIds 负责的客户
                userIdsQueryBuilder = QueryBuilders.matchQuery(userIdsStr, "ownerUserIdStr");
            }else if(2 == prole){
                //userIds 参与的客户
                userIdsQueryBuilder = QueryBuilders.matchQuery(userIdsStr, "collaborator");
            }else{
                throw new Exception("prole 参数非法!");
            }
            
            queryBuilder = queryBuilder.must(userIdsQueryBuilder);
        }
        
        Advanc advanc = new Advanc();
        advanc.setPageSortHighLight(pageSortHighLight);
        advanc.setIncludes(new String[]{"id","ownerUserId","createUserId"});
//        advanc.setExcludes(new String[]{"ownerUserIdStr","teamUserIds"});
        //注意：如果includes为null的情况下excludes中包含用match的条件，设置了excludes也无效

        return esSearchTemplate.search(queryBuilder, advanc, ESCustomer.class);
    }


    @Override
    public Paginator<ESCustomer> searchByPool(String keyword,Integer level,Integer source, Integer pageNum, Integer pageSize) throws Exception {
        PageSortHighLight pageSortHighLight = new PageSortHighLight(pageNum, pageSize);
        
        //公海
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("ownerUserId", 0L));
        
        if(StrUtil.isNotBlank(keyword)){

            QueryBuilder keywordQueryBuilder = QueryBuilders.boolQuery().should(QueryBuilders.matchPhrasePrefixQuery("name", keyword).maxExpansions(50))
                   .should(QueryBuilders.queryStringQuery("*"+keyword+"*").field("mobile"))
                   .should(QueryBuilders.queryStringQuery("*"+keyword+"*").field("telephone"));
           
            queryBuilder = queryBuilder.must(keywordQueryBuilder);
           
           HighLight highLight = pageSortHighLight.getHighLight();
           highLight.field("name");
           highLight.field("mobile");
           highLight.field("telephone");
        }
        
        if(source != null ){
            queryBuilder = queryBuilder.must(QueryBuilders.termQuery("source", source));
        }
        
        if(level != null ){
            queryBuilder = queryBuilder.must(QueryBuilders.termQuery("level", level));
        }
        
        Advanc advanc = new Advanc();
        advanc.setPageSortHighLight(pageSortHighLight);
        
//        advanc.setIncludes(new String[]{"*"});
//        advanc.setExcludes(new String[]{"ownerUserIdStr","teamUserIds"});
        //注意：如果includes为null的情况下excludes中包含用match的条件，设置了excludes也无效

        return esSearchTemplate.search(queryBuilder, advanc, ESCustomer.class);
    }
    
}
